<?php
class DigCms_Plugin_PageHead extends Zend_Controller_Plugin_Abstract {

    protected $_view = null;
    protected $_item = null;
    protected $_settings = array();

    public function postDispatch(Zend_Controller_Request_Abstract $request) {
        $this->_view = Zend_Layout::getMvcInstance()->getView();
        $this->_item = $request->getParam(DigCms_Library_Item_Controller::CURRENT_ITEM);
        $this->_settings = Dig_Service_Module::settings('digCms');
        if($this->_item) {
            $this->_setTitle();
            $this->_setMetaData();
        }
    }

    protected function _setTitle() {
        if(! empty($this->_item->page_title) && substr($this->_item->page_title, 0, 1) == '/') {
            $title = $this->_item->page_title;
            $title = substr($title, 1, strlen($title) - 1);
            $this->_view->headTitle(html_entity_decode($title));
        } else {
            $siteRootId = Dig_Service_Module::settings('digCms', 'siteRootId');
            // set the page title
            $titleFields = $this->_settings['head']['title']['fields'];
            $titleParts[] = $this->_item->overloadContent($titleFields);
            $parents = $this->_item->parents();
            if($parents && $this->_item->id != $siteRootId) {
                foreach ($parents as $parentItem) {
                    if($parentItem->id == $siteRootId) {
                        break;
                    }
                    $titlePart = $parentItem->overloadContent($titleFields);
                    $break = false;
                    if(substr($titlePart, 0, 1) == '/') {
                        $titlePart = substr($titlePart, 1, strlen($titlePart) - 1);
                        $break = true;
                    }
                    $titleParts[] = $titlePart;
                    if($break == true) {
                        break;
                    }
                }
            }
            foreach ($titleParts as $part) {
                $part = ucwords(str_replace('_', ' ', $part));
                $this->_view->headTitle(html_entity_decode($part));
            }
            $this->_view->headTitle()->setSeparator($this->_settings['head']['title']['separator']);
        }
    }

    protected function _setMetaData() {
        $this->_view->headMeta()->appendName('description', $this->_item->inheritContent('meta_description'));
        $this->_view->headMeta()->appendName('keywords', $this->_item->inheritContent('meta_keywords'));
    }
}
?>